﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity.Infrastructure;
using System.Data;
using Framework.Infrastructure.Context;
using Framework.Infrastructure.IoC;
using System.Linq.Expressions;
using Framework.Infrastructure;

namespace Framework
{
    public class DbContextAttribute : System.Attribute
    {
        public string DbContextType { get; set; }
        public DbContextAttribute(string type)
        {
            DbContextType = type;
        }
    }

    public abstract class DbEntity : EventEntity
    {
        DbEntityEntry _entityEntry;
        internal DbEntityEntry EntityEntry
        {
            get
            {
                return _entityEntry ?? (_entityEntry = DbContext.Entry(this));
            }
            set
            {
                _entityEntry = value;
            }
        }
        MSDbContext _dbContext;
        protected MSDbContext DbContext
        {
            get
            {
                if (_dbContext == null)
                {
                    if (DbContextType != null)
                    {
                        _dbContext = IoCFactory.Resolve(DbContextType) as MSDbContext;
                    }
                    else
                    {
                        _dbContext = IoCFactory.Resolve<MSDbContext>();
                    }
                }

                return _dbContext;
            }
        }

        Type DbContextType
        {
            get
            {
                var attr = this.GetCustomAttribute<DbContextAttribute>();
                if (attr != null)
                {
                    return Type.GetType(attr.DbContextType);
                }
                return null;
            }
        }

        public void MarkAsDeleted()
        {
            EntityEntry.State = EntityState.Deleted;
        }

        public void MarkAsAdded()
        {
            EntityEntry.State = EntityState.Added;
        }

        public void MarkAsModified()
        {
            EntityEntry.State = EntityState.Modified;
        }

        public void MarkAsUnchanged()
        {
            EntityEntry.State = EntityState.Unchanged;
        }
    }
}
